<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $helpers = array('Html', 'Form');
	var $components = array('Auth');
	var $uses = array('User', 'Friend');

	
	
	
		/* This function is meant to be called by requestAction */
	/* it's primary purpose is for the site autocomplete search */
	/* which is called from the cities controller via RequestAction */
	function findUsers($query, $limit=3)
	{
		
		$this->User->unbindModel(array('hasAndBelongsToMany' => array( 'Friend')));
		$this->User->unbindModel(array('hasMany' => array('Story')));
		$this->User->Profile->unbindModel(array('hasMany' => array('Post')));
		$this->User->Profile->unbindModel(array('belongsTo' => array('User')));
		$this->User->Profile->City->unbindModel(array('hasMany' => array('Profile','Story','Post')));
		$this->User->Profile->City->unbindModel(array('hasAndBelongsToMany' => array('Profile')));
		$this->User->Profile->Image->unbindModel(array('belongsTo' => array('Profile')));
		
		$result = $this->User->find('all', array(
			 'conditions' => array(
			 	'User.username LIKE' =>  $query . '%'
			 	),
			 'recursive' => 3,
			 'limit' => $limit
			 ));
	
			 
		return $result; /* this returns to another function */
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid user.', true));
			$this->redirect('/');
		}
		else
		{
			//$this->User->unbindModel(array('hasAndBelongsToMany' => array('Friend')));
		
			$this->User->recursive = 1;
			$usr = $this->User->read(null,$id);
			
			if(isset($usr['Profile']['id']))
			 $this->redirect(array('controller' => 'profiles', 'action' => 'view', $usr['Profile']['id']));
			else
			 $this->redirect('/');
			
		}		
	}
	
	function addFriend($friend_id)
    {
    	$user = $this->Auth->user();
    	$user_id = $user['User']['id'];
    	
    	$profile = $this->User->Profile->findByUserId($friend_id);
    	$myprofile = $this->User->Profile->findByUserId($user_id);
    	
    	if($user_id == $friend_id)
    	{
    		$this->Session->setFlash(__('Unable to add yourself as friend.', true));
    		$this->redirect(array('controller' => 'profiles', 'action' => 'view', $myprofile['Profile']['id']));
    	}
    	
   		if (!$profile) {
			$this->Session->setFlash(__('Unable to add nonexisting user as friend.', true));
			$this->redirect(array('controller' => 'profiles', 'action' => 'view', $myprofile['Profile']['id']));
		}

    	$this->Friend->recursive = -1;
    	$existing = $this->Friend->find('all',
    		array('conditions' =>  
    						array('OR' => 
    							array(
    								array('Friend.user_id' => $friend_id, 'Friend.friend_id' => $user_id),
    								array('Friend.user_id' => $user_id, 'Friend.friend_id' => $friend_id)
    								))
    			 		
    			 ));
    			  	
    			 
	    if(empty($existing))
	    {
	    		$this->Friend->addFriend($friend_id,$user_id);
	    		$this->Session->setFlash(__('You are now friends.', true));
	    		$this->redirect(array('controller' => 'profiles', 'action' => 'view', $profile['Profile']['id']));
	    }
	    else
	    {
	    	if(!empty($existing))
	    		$this->Session->setFlash(__('You\'re already friends.', true));
			else
				$this->Session->setFlash(__('Unable to add as friend.', true));
			
	    	$this->redirect(array('controller' => 'profiles', 'action' => 'view', $profile['Profile']['id']));
	    }
	       	
    }
	
	function add() {
		$user = $this->Auth->user();
		if ($user)
	    {
	    	$user_id = $user['User']['id'];
	    	$profile = $this->User->Profile->findByUserId($user_id);
	    	
	    	$this->Session->setFlash(__('You must be logged out to do that.', true));
	    	$this->redirect(array('controller' => 'profiles', 'action' => 'view', $profile['Profile']['id']));
	    }
		
		if (!empty($this->data)) {
			$formError = false;
			if(empty($this->data['User']['username']))
			{
				$this->set('erremptyusername',true);
				unset($this->data['User']['username']);
				$formError = true;
				$this->Session->setFlash(__('Error. Try Again.', true));
			}
			/*
			if(empty($this->data['User']['email']))
			{
				$this->set('erremptyemail',true);
				unset($this->data['User']['email']);
				$formError = true;	
				$this->Session->setFlash(__('Error. Try Again.', true));
			}*/
			
			if($this->data['User']['password'] == $this->Auth->password(''))
			{
				$this->set('erremptypassword',true);
				unset($this->data['User']['password']);
				unset($this->data['User']['verify_password']);
				$formError = true;
				$this->Session->setFlash(__('Error. Try Again.', true));
			}
			else if($this->data['User']['password'] != $this->Auth->password($this->data['User']['verify_password']))
			{
				$this->set('errPasswordMatch',true);
				unset($this->data['User']['password']);
				unset($this->data['User']['verify_password']);
				$formError = true;	
				$this->Session->setFlash(__('Error. Try Again.', true));
			}

			if(empty($this->data['User']['first_name']))
			{
				$this->set('erremptyfname',true);
				unset($this->data['User']['first_name']);
				$formError = true;
				$this->Session->setFlash(__('Error. Try Again.', true));
			}
			
			if(empty($this->data['User']['last_name']))
			{
				$this->set('erremptylname',true);
				unset($this->data['User']['last_name']);
				$formError = true;
				$this->Session->setFlash(__('Error. Try Again.', true));
			}
			
			if(empty($this->data['City']['id']) || $this->data['City']['id'] == 0)
			{
				$this->set('errhometown',true);
				unset($this->data['City']);
				$formError = true;
			}
			
		
			$this->User->set($this->data);
			if(!$this->User->validates())
			{
				$formError = true;
			}
			if(strlen($this->data['User']['verify_password']) < 6)
			{
				$this->set('leastSix', true);
			}
			
			if(!$formError)
			{
				$this->User->create();
				$this->data['User']['confirmation_code'] = '0';
				$this->data['User']['confirmed'] = 1;
				$city = $this->data['City'];
				unset($this->data['City']);
				
				if($this->User->save($this->data))
				{
					$this->User->Profile->create();
					$this->data['Profile']['user_id'] = $this->User->id;
					$this->data['Profile']['city_id'] = $city['id'];
					$usr = $this->data['User'];
					unset($this->data['User']);
					$this->User->Profile->save($this->data);
					$this->User->Profile->Image->create();
					$this->data['Image']['profile_id'] = $this->User->Profile->id;
					$this->data['Image']['filename'] = 'profile_blank.jpg';
					unset($this->data['Profile']);
					$this->User->Profile->Image->save($this->data);
					$this->Auth->login($usr);
					$this->Session->setFlash(__('The user has been saved.', true));
					$this->redirect(array('controller'=>'profiles' , 'action'=>'edit'));
				} 
				else 
				{
					unset($this->data['User']['password']);
					unset($this->data['User']['verify_password']);
					$this->Session->setFlash(__('Error. Try again.', true));
				}
			}
			else
			{
				unset($this->data['User']['password']);
				unset($this->data['User']['verify_password']);
				$this->Session->setFlash(__('Error. Try Again.', true));
				$this->render();
			}
			
			$users = $this->User->find('list');
			$this->set(compact('users'));
		}
		
	}
	
      function change_password() {
               $user = $this->Auth->user();
               $user_id = $user['User']['id'];
               $this->User->recursive = -1;
               $user_data = $this->User->findById($user_id);
               if(!empty($this->data))
               {
                       $user_password = $user_data['User']['password'];
                       if($user_password == $this->Auth->password($this->data['User']['current_password']))
                       {
                       		if(empty($this->data['User']['new_password']))
                       		{
                       			$this->Session->setFlash(__('Error. Try Again.', true));
                       			$this->set('leastSix', true);
                       			$this->render();
                       		}
                       		
                            else if($this->data['User']['new_password'] != $this->data['User']['confirm_npassword'])
                            {
								unset($this->data['User']['new_password']);
								unset($this->data['User']['confirm_npassword']);
								$this->set('errPasswordMatch', true);
                                $this->Session->setFlash(__('Passwords do not match.', true));
                                $this->render();
                            }
                            else if(strlen($this->data['User']['new_password']) < 6)
                            {
                            	unset($this->data['User']['new_password']);
								unset($this->data['User']['confirm_npassword']);
								$this->set('leastSix', true);
								$this->Session->setFlash(__('Error. Try Again.', true));
								$this->render();
                            } 
                            else
                            {
                               	$user_npassword = $this->Auth->password($this->data['User']['new_password']);
                                $this->User->id = $user_id;
                                $this->User->saveField('password', $user_npassword);
                               	$this->Session->setFlash(__('Your password has been changed.', true));
                                $this->redirect(array('controller'=>'profiles' , 'action'=>'view'));

                            }
						}
                       else
                       {
							unset($this->data['User']['current_password']);
							unset($this->data['User']['new_password']);
							unset($this->data['User']['confirm_npassword']);
							$this->set('errPasswordwrong', true);
                       		$this->Session->setFlash(__('Incorrect password. Try again.', true));
                       		$this->render();
                       }
               }
               
               else
               {
               		$this->render();
               }
       }
       
	
	    /**
     *  The AuthComponent provides the needed functionality
     *  for login, so you can leave this function blank.
     */
    function login() {
    	$user = $this->Auth->user();
    	if ($user)
    	{
    		$user_id = $user['User']['id'];
    		$profile = $this->User->Profile->findByUserId($user_id);
    		
    		$this->Session->setFlash(__('You are already logged in.', true));
    		$this->redirect(array('controller' => 'profiles', 'action' => 'view', $profile['Profile']['id']));
    	}
    }
    
    function beforeFilter() {
    	$this->Auth->allow('add','findUsers');
    	$this->Auth->loginRedirect = array('controller' => 'Profiles', 'action' => 'view');
    	$this->Auth->authenticate = $this->User;
    }

    function logout() {
        $this->redirect($this->Auth->logout());
    }

}
?>